<template>
  <div class="aa">
    <el-row>
      <el-col :span="2">
        <el-radio-group v-model="type" size="medium" @change="radiochange">
          <el-radio-button v-for="(item, index) in typeOption" :key="index" :label="item.value">{{ item.label }}</el-radio-button>
        </el-radio-group>
        <el-button type="primary" size="mini" @click="cleanCanvans">清空</el-button>
      </el-col>
      <el-col :span="10">
        <div id="videobox" class="cc" style="width:400px">
          <!-- <video id="myvideo" autoplay width="400px" height="300px"></video> -->
          <!-- <video id="myvideo" autoplay width="100%" height="300px"></video> -->
          <video id="myvideo" autoplay width="100%" height="100%" @canplay="videoLoad()"></video>

          <div id="canvasbaox" class="bb">
            <canvas
              ref="tagcanvas"
              @mousedown="mouseDown($event)"
              @mouseup="mouseUp($event)"
              @mousemove="mouseMove($event)"
              @contextmenu.prevent="contextMenu($event)"
            ></canvas>
          </div>
        </div>
      </el-col>
      <el-col :span="10">
        <div>sdfsdfsdfsd</div>
        <el-form>
          <el-form-item>
            <el-button type="primary" @click="onSavePoint()">保存</el-button>
          </el-form-item>
          <el-form-item>
            <el-input type="textarea" :autosize="{ minRows: 6, maxRows: 12}" v-model="frmPoints"></el-input>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import flvjs from "flv.js";

export default {
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    // 这里存放数据
    return {
      frmPoints: "",

      type: "R",
      typeOption: [
        { label: "矩形", value: "R" },
        { label: "多边形", value: "A" },
      ],

      player: null,

      //线段的点的集合，当前操作的
      points: [],
      //可拖动圆圈的点的集合，当前操作的
      circles: [],

      // 绘制的图的集合
      allcans: [
        // {
        //   key: "",
        //   type: "",
        //   pointdata: [],
        //   circledata: [],
        //   isComplete: false,
        //    color: "red",
        // },
      ],

      // canvans 变量
      ctx: "",
      //点的大小。 圆半经、矩形的
      radius: 3,
      color: "red",
      //填空
      fillColor: "red",
      fillColorUnchk: "transparent",
      //线
      stockColor: "red",
      lineWidth: 1.5,
      //鼠标指针在所绘图的位置，图形里面 in，外面 out,转角点上 on，线上 online
      //如果是in，可对图形进行拖到；是 on，可以转变大小；
      position: "out",

      //选中的图形有下序号，数组下标
      chkType: "",
      index: -1,
      indexPic: -1,
      key: -1,
      //移动或者拖动时，原来的 位置
      oldX: 0,
      oldY: 0,

      isNow: false,

      //是否鼠标右键
      isRightClick: false,
      isLeftDown: false,
      //拖动矩形，不改变大小
      drag: false,
      //改变原大小
      resize: false,
      //画新矩形
      draw: false,

      //移支图形前的
      oldpoints: [],
      //可拖动圆圈的点的集合， 
      oldcircles: [],

    };
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    cleanCanvans() {
      let dom = this.$refs.tagcanvas;
      this.ctx.clearRect(0, 0, dom.width, dom.height);
      this.allcans = [];
      this.circles = [];
      this.points = [];
    },
    radiochange(_val) {
      if (_val != "A") {
        if (this.points.length) {
          let cntnow = this.allcans.length || 1;
          cntnow = cntnow + 1;
          let tmp = {
            key: "key" + cntnow,
            type: "A",
            pointdata: Object.assign([], this.points),
            circledata: Object.assign([], this.circles),
            isComplete: true,
          };

          this.allcans.push(tmp);
        }
        this.circles = [];
        this.points = [];
      }
    },
    mouseDown(e) {
      let dom = this.$refs.tagcanvas;

      if (e.button == 0) this.isLeftDown = true;

      this.createAdown(e, dom);
    },
    mouseUp(e) {
      let dom = this.$refs.tagcanvas;

      this.createAup(e, dom);

      this.isLeftDown = false;
      // this.resize = false;
      // this.drag = false;
    },
    mouseMove(e) {
      let dom = this.$refs.tagcanvas;
      this.createAmove(e, dom);
    },
    contextMenu(e) {
      window.console.log(e);
      return false;
    },
    /**
     * 绘制 图形 鼠标按下时的操作
     */
    createAdown(e, dom) {
      if (e.button == 2) {
        //如果是右键，此次画图结束,把当次的所有的点存起来，针对的是画不规则图形
        let cntnow = this.allcans.length || 1;
        cntnow = cntnow + 1;
        let tmp = {
          key: "key" + cntnow,
          type: this.type,
          pointdata: Object.assign([], this.points),
          circledata: Object.assign([], this.circles),
          isComplete: true,
        };

        this.allcans.push(tmp);

        this.circles = [];
        this.points = [];

        this.isRightClick = true;
        return;
      }

      var clickX = e.offsetX;
      var clickY = e.offsetY;

      //如果是点击在所会图形上，跳过，是拖动、绽放操作
      let ptmp = {
        x: e.offsetX - dom.offsetLeft,
        y: e.offsetY - dom.offsetTop,
      };
      if (this.allcans.length) {
        for (let aindex = 0; aindex < this.allcans.length; aindex++) {
          let dtmp = this.rayCastingCopy(ptmp, this.allcans[aindex].pointdata);
          if (dtmp.position != "out") {
            this.position = dtmp.position;
            this.chkType = this.allcans[aindex].type;
            this.indexPic = aindex;
            this.index = dtmp.index;
            if (this.index > -1) {
              this.oldX = this.allcans[aindex].pointdata[this.index].x;
              this.oldY = this.allcans[aindex].pointdata[this.index].y;
            }
            this.oldpoints = JSON.parse(
              JSON.stringify(this.allcans[aindex].pointdata)
            );
            this.oldcircles = JSON.parse(
              JSON.stringify(this.allcans[aindex].circledata)
            );
            break;
          }
        }
      }
      if (this.points.length) {
        this.isNow = false;
        let dtmp = this.rayCastingCopy(ptmp, this.points);
        if (dtmp.position != "out") {
          this.position = dtmp.position;
          this.index = dtmp.index;
          if (this.index > -1) {
            this.oldX = this.points[this.index].x;
            this.oldY = this.points[this.index].y;
          }
          this.isNow = true;
          this.oldpoints = JSON.parse(JSON.stringify(this.points));
          this.oldcircles = JSON.parse(JSON.stringify(this.circles));
        }
      }

      if (this.position == "on") {
        this.resize = true;
        return;
      } else if (this.position == "in" || this.position == "online") {
        this.oldX = e.offsetX;
        this.oldY = e.offsetY;
        this.drag = true;
        return;
      }
      if (this.position != "out") {
        return;
      }

      //如果点击新的位置，则进入下面的代码，绘制点
      //先清空之前的，再重新画
      this.ctx.clearRect(0, 0, dom.width, dom.height);

      if (this.type == "A") {
        //把当前画圆点放入数组中
        var circle = this.Circle(clickX, clickY);
        this.circles.push(circle);

        // 把当前画线点放入数组中
        var point = this.Point(clickX, clickY);
        this.points.push(point);
      } else if (this.type == "R") {
        this.oldX = clickX;
        this.oldY = clickY;
      }

      //画图形
      this.restCanvans();

    },
    createAmove(e, dom) {
      let ptmp = {
        x: e.offsetX - dom.offsetLeft,
        y: e.offsetY - dom.offsetTop,
      };
      // debugger;
      this.position = "out";
      if (this.allcans.length) {
        for (let aindex = 0; aindex < this.allcans.length; aindex++) {
          let dtmp = this.rayCastingCopy(ptmp, this.allcans[aindex].pointdata);
          if (dtmp.position != "out") {
            this.position = dtmp.position;
            break;
          }
        }
      }
      if (this.points.length) {
        let dtmp = this.rayCastingCopy(ptmp, this.points);
        if (dtmp.position != "out") {
          this.position = dtmp.position;
        }
      }

      if (this.position == "in") {
        this.$refs.tagcanvas.style.cursor = "move";
      } else if (this.position == "on") {
        this.$refs.tagcanvas.style.cursor = "pointer";
      } else if (this.position == "online") {
        this.$refs.tagcanvas.style.cursor = "move";
      } else {
        this.$refs.tagcanvas.style.cursor = "default";
      }

      if (!this.isLeftDown) {
        return;
      }

      let x1 = e.offsetX - dom.offsetLeft;
      let y1 = e.offsetY - dom.offsetTop;
      if (this.resize) {
        //拖动一个点，改变原有的大小
        this.ctx.clearRect(0, 0, dom.width, dom.height);
        //拖动一个点
        if (this.isNow) {
          this.circles[this.index].x = x1;
          this.circles[this.index].y = y1;
          this.points[this.index].x = x1;
          this.points[this.index].y = y1;

          if (this.type == "A") {
          } else {
            let mvx = x1 - this.oldX;
            let mvy = y1 - this.oldY;

            let nextIndex = this.index + 1;
            if (nextIndex >= this.points.length) {
              nextIndex = 0;
            }
            this.circles[nextIndex].x = this.circles[nextIndex].x + mvx;
            this.circles[nextIndex].y = this.circles[nextIndex].y + mvy;
            this.points[nextIndex].x = this.points[nextIndex].x + mvx;
            this.points[nextIndex].y = this.points[nextIndex].y + mvy;

            let preIndex = this.index - 1;
            if (preIndex < 0) {
              preIndex = this.points.length - 1;
            }
            this.circles[preIndex].x = this.circles[preIndex].x + mvx;
            this.circles[preIndex].y = this.circles[preIndex].y + mvy;
            this.points[preIndex].x = this.points[preIndex].x + mvx;
            this.points[preIndex].y = this.points[preIndex].y + mvy;

            // let pointsTmp = this.calcRectNowPoints(this.circles,this.oldY,x1,y1);
            // this.points = JSON.parse(JSON.stringify(pointsTmp));
            // this.circles = JSON.parse(JSON.stringify(pointsTmp));
          }
        } else {
          // debugger;

          let mvx = x1 - this.oldX;
          let mvy = y1 - this.oldY;

          this.allcans[this.indexPic].circledata[this.index].x = x1;
          this.allcans[this.indexPic].circledata[this.index].y = y1;
          this.allcans[this.indexPic].pointdata[this.index].x = x1;
          this.allcans[this.indexPic].pointdata[this.index].y = y1;
          if (this.type == "A") {
          } else if (this.type == "R") {
            let curPoints = this.allcans[this.indexPic].pointdata;
            let curCircles = this.allcans[this.indexPic].circledata;
            let nextIndex = this.index + 1;
            if (nextIndex >= curPoints.length) {
              nextIndex = 0;
            }
            let preIndex = this.index - 1;
            if (preIndex < 0) {
              preIndex = curPoints.length - 1;
            }
            if (this.oldpoints[this.index].x == this.oldpoints[nextIndex].x) {
              curPoints[nextIndex].x = this.oldpoints[nextIndex].x + mvx;
              curCircles[nextIndex].x = this.oldcircles[nextIndex].x + mvx;
            }
            if (this.oldpoints[this.index].y == this.oldpoints[nextIndex].y) {
              curPoints[nextIndex].y = this.oldpoints[nextIndex].y + mvy;
              curCircles[nextIndex].y = this.oldcircles[nextIndex].y + mvy;
            }

            if (this.oldpoints[this.index].x == this.oldpoints[preIndex].x) {
              curPoints[preIndex].x = this.oldpoints[preIndex].x + mvx;
              curCircles[preIndex].x = this.oldcircles[preIndex].x + mvx;
            }
            if (this.oldpoints[this.index].y == this.oldpoints[preIndex].y) {
              curPoints[preIndex].y = this.oldpoints[preIndex].y + mvy;
              curCircles[preIndex].y = this.oldcircles[preIndex].y + mvy;
            }
          }
        }

        this.restCanvans();
      } else if (this.drag) {
        //拖动整个图形，改变位置
        this.ctx.clearRect(0, 0, dom.width, dom.height);

        if (this.isNow) {
          for (let i = 0; i < this.circles.length; i++) {
            this.circles[i].x = x1 - this.oldX + this.oldcircles[i].x;
            this.circles[i].y = y1 - this.oldY + this.oldcircles[i].y;
            this.points[i].x = x1 - this.oldX + this.oldpoints[i].x;
            this.points[i].y = y1 - this.oldY + this.oldpoints[i].y;
          }
        } else {
          for (
            let i = 0;
            i < this.allcans[this.indexPic].circledata.length;
            i++
          ) {
            this.allcans[this.indexPic].circledata[i].x =
              x1 - this.oldX + this.oldcircles[i].x;
            this.allcans[this.indexPic].circledata[i].y =
              y1 - this.oldY + this.oldcircles[i].y;
            this.allcans[this.indexPic].pointdata[i].x =
              x1 - this.oldX + this.oldpoints[i].x;
            this.allcans[this.indexPic].pointdata[i].y =
              y1 - this.oldY + this.oldpoints[i].y;
          }
        }
        this.restCanvans();
      } else {
        //如果是矩形，移动时，就绘制出相应的矩形
        if (this.type == "R") {
          let mvx = x1 - this.oldX;
          let mvy = y1 - this.oldY;
          if (mvx == 0 && mvy == 0) {
            return;
          }
          let pointsTmp = this.calcRectNowPoints(this.oldX, this.oldY, x1, y1);
          this.points = JSON.parse(JSON.stringify(pointsTmp));
          this.circles = JSON.parse(JSON.stringify(pointsTmp));
        }
        this.ctx.clearRect(0, 0, dom.width, dom.height);
        this.restCanvans();
      }
    },
    createAup(e, dom) {
      this.isRightClick = false;
      this.position = "out";


      //矩形绘制时， 鼠标放开时，此矩形绘制完成
      if (this.type == "R" && !this.resize && !this.drag) {
        let cntnow = this.allcans.length || 1;
        cntnow = cntnow + 1;
        let tmp = {
          key: "key" + cntnow,
          type: this.type,
          pointdata: Object.assign([], this.points),
          circledata: Object.assign([], this.circles),
          isComplete: true,
        };

        this.allcans.push(tmp);
        this.points = [];
        this.circles = [];
      }

      this.resize = false;
      this.drag = false;
    },

    /**
     * 多边形的每个点的坐标
     */
    Point(x, y) {
      return {
        x: x,
        y: y,
      };
    },
    /**
     * 多边形每个点的圈的坐标
     */
    Circle(x, y) {
      return {
        x: x,
        y: y,
        // radius: this.radius,
        // color: this.color,
      };
    },

    /**
     * 矩形的坐标
     */
    PointRect(x, y, h, w) {
      return {
        x: x,
        y: y,
        h: h,
        w: w,
      };
    },

    /**
     * 判断点是否在多边形内部
     */
    rayCastingCopy(p, poly) {
      let index = -1;

      let ret = { index: -1, position: "out" };

      var px = p.x,
        py = p.y,
        flag = false;

      let arcR = this.radius;
      for (var i = 0, l = poly.length; i < l; i++) {
        var sx = poly[i].x,
          sy = poly[i].y;
        var j = i + 1;
        if (j == poly.length) j = 0;
        var tx = poly[j].x,
          ty = poly[j].y;

        // 点与多边形顶点重合
        if (sx === px && sy === py) {
          // debugger;
          ret.index = i;
          ret.position = "on";
          return ret;
        }

        if (
          sx - arcR < px &&
          px < sx + arcR &&
          sy - arcR < py &&
          py < sy + arcR
        ) {
          ret.index = i;
          ret.position = "on";
          return ret;
        }

        // 判断线段两端点是否在射线两侧
        if ((sy < py && ty >= py) || (sy >= py && ty < py)) {
          // 线段上与射线 Y 坐标相同的点的 X 坐标
          var x = sx + ((py - sy) * (tx - sx)) / (ty - sy);

          // 点在多边形的边上
          if (x === px) {
            ret.index = i;
            ret.position = "online";
            return ret;
          }

          // 射线穿过多边形的边界
          if (x > px) {
            flag = !flag;
          }
        }
      }

      // 射线穿过多边形边界的次数为奇数时点在多边形内
      let retFlag = flag ? "in" : "out";
      ret.index = -1;
      ret.position = retFlag;
      return ret;
      // return retFlag;
    },

    /**
     * 画所有的图形
     */
    restCanvans() {
      if (this.points.length) {
        this.drawA(this.points);
      }
      if (this.circles.length) {
        this.drawArc(this.circles);
      }

      if (!this.allcans.length) {
        return;
      }

      // debugger;
      for (var ind = 0; ind < this.allcans.length; ind++) {
        let _nowDatas = this.allcans[ind];
        // 画线的顶点的圈
        if (_nowDatas.circledata.length) this.drawArc(_nowDatas.circledata);
        // 画线
        if (_nowDatas.pointdata.length) this.drawA(_nowDatas.pointdata);
      }
    },
    /**
     * 画出多边形的各个边
     */
    drawA(pointdata) {
      // 画线

      this.ctx.beginPath();
      this.ctx.lineWidth = this.lineWidth;
      //从起始点开始绘制
      let pointstmp = pointdata;
      this.ctx.moveTo(pointstmp[0].x, pointstmp[0].y);
      for (var i = 0; i < pointstmp.length; i++) {
        this.ctx.lineTo(pointstmp[i].x, pointstmp[i].y);
        if (i > 1 && i == pointstmp.length - 1) {
          this.ctx.lineTo(pointstmp[0].x, pointstmp[0].y);
        }
      }
      this.ctx.fillStyle = this.fillColorUnchk; //"red";
      this.ctx.fill();
      this.ctx.strokeStyle = this.stockColor; //"red";
      this.ctx.stroke();
    },
    /**
     * 画顶点的圆圈
     */
    drawArc(circledata) {
      for (var i = 0; i < circledata.length; i++) {
        var circle = circledata[i];
        // 绘制圆圈
        this.ctx.beginPath();
        this.ctx.lineWidth = this.lineWidth;
        this.ctx.arc(circle.x, circle.y, this.radius, 0, Math.PI * 2);
        // debugger;
        this.ctx.fillStyle = this.fillColorUnchk;
        this.ctx.strokeStyle = this.stockColor;
        this.ctx.fill();
        this.ctx.stroke();
      }
    },

    calcRectNowPoints(x, y, xm, ym) {
      let points = [];
      points.push(this.Point(x, y));
      points.push(this.Point(x, ym));
      points.push(this.Point(xm, ym));
      points.push(this.Point(xm, y));

      return points;
    },
    calcRpoints(rectPoint) {
      let x = rectPoint.x;
      let y = rectPoint.y;
      let h = rectPoint.h;
      let w = rectPoint.w;

      let points = [];
      points.push(this.Point(x, y));
      points.push(this.Point(x, y + w));
      points.push(this.Point(x + h, y + w));
      points.push(this.Point(x + h, y));

      return points;
    },


    chgCanvasSize() {
      let video = document.querySelector("#myvideo");

      let vanvasbox = document.querySelector("#canvasbaox");

      vanvasbox.style.left = video.offsetLeft;
      vanvasbox.style.top = video.offsetTop;
      vanvasbox.style.width = video.offsetWidth + "px";
      vanvasbox.style.height = video.offsetHeight + "px";

      let dom = this.$refs.tagcanvas;
      dom.width = video.offsetWidth;
      dom.height = video.offsetHeight;

    },
    videoLoad() { 
      // debugger;
      this.chgCanvasSize();

    },
    onSavePoint() {
      this.frmPoints = "";
      for (let index = 0; index < this.allcans.length; index++) {
        const element = this.allcans[index];
        const curType = element.type;
        // this.frmPoints = this.frmPoints.concat(curType, ",");
        // if (curType == "R") { 
          this.frmPoints = this.frmPoints.concat(this.tranXYtoStr(curType, element.pointdata), "|");
        // } else {
        //   this.frmPoints = this.frmPoints.concat(this.tranXYtoStr(curType, element.pointdata), "|");
        // } 

      }
    },

    tranXYtoStr(type, points) {
      let video = document.querySelector("#myvideo")
      let videoW = video.offsetWidth;
      let videoH = video.offsetHeight;

       if (type == "R") {
        let width = (points[1].y - points[0].y) / videoW;
        let heigth = (points[3].x - points[0].x) / videoH;
        return "(" + width + "," + heigth + ")"
      } else if (type == "A") {

        let tmpPoints = [];
        for (const index in points) {
          const item = points[index];
          let x = item.x/videoH; let y =  item.y/videoW;
          tmpPoints.push("(" + x + "," + y + ")");
        }

        return tmpPoints.toString();
      }
    },
 

},
// 生命周期 - 创建完成（可以访问当前this实例）
created() {
  if (flvjs.isSupported()) {
    this.player = flvjs.createPlayer({
      type: "flv",
      isLive: true,
      cors: true,
      url: "http://d.ossrs.net/live/livestream.flv",
    });
  }
},
// 生命周期 - 挂载完成（可以访问DOM元素）
mounted() {
  var video = document.querySelector("#myvideo");
  this.player.attachMediaElement(video);
  this.player.load();
  // this.player.play();
 
  this.chgCanvasSize()
  // debugger;

  this.ctx = this.$refs.tagcanvas.getContext("2d");

},
beforeCreate() { }, // 生命周期 - 创建之前
beforeMount() { }, // 生命周期 - 挂载之前
beforeUpdate() { }, // 生命周期 - 更新之前
updated() { }, // 生命周期 - 更新之后
beforeDestroy() { }, // 生命周期 - 销毁之前
destroyed() { }, // 生命周期 - 销毁完成
activated() { }, // 如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped>
.bb {
  position: absolute;
  /* top: 0%;
    left: 0%; */
  /* width: 100%;
  height: 100%; */
  background-color: transparent;
  z-index: 1001;
  -moz-opacity: 0.7;
  opacity: 0.7;
  filter: alpha(opacity=10);
}
.cc {
  position: relative;
}
canvas {
  position: absolute;
  top: 0;
  left: 0;
}
</style>
